from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib

import hmac
import base64
from hashlib import sha256
import urllib

#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#导入正则
import re

import cv2


import json

from myapp.models import User,Goods
from myapp.myser import GoodsSer


import redis

#定义ip和端口
host = 'localhost'
port = 6379

#建立连接
r = redis.Redis(host=host,port=port)




import json

#格式化结果集
def dictfetch(cursor):

    #声明描述符
    desc = cursor.description

    return [ dict( zip([col[0] for col in desc],row )) 
            for row in cursor.fetchall()
    ]



#搜索接口
class Searchs(APIView):

    def get(self,request):

        #检索字段
        text = request.GET.get('text',None)

        #转换数据类型
        text = json.loads(text)

        sql = ''
        #动态拼接
        for val in text:
            sql += "or name like '%%%s%%' " % val

        sql  = sql.lstrip('or')
        #建立游标对象
        cursor = connection.cursor()
        
        #执行sql
        cursor.execute("select desc,name,id,img,price, from goods where id !=0 and (" + sql + ")")

        #查询
        result = dictfetch(cursor)
        print(result)
        return Response({
            'data':result
        })


#商品列表页
class GoodsLists(APIView):

    def get(self,request):

        #检索字段
        text = request.GET.get('text',None)

        #排序字段
        coloum = request.GET.get('coloum',None)

        #排序方案
        sort_order = request.GET.get('order','')

        print(coloum,sort_order)

        #当前页
        page = request.GET.get('page',1)

        #一页显示个数
        size = request.GET.get('size',1)

        #计算从哪儿开始切
        data_start = (int(page)-1)*int(size)
        #计算切到哪儿
        data_end = int(page) * int(size)


        if coloum:
            keyword = sort_order+coloum
            goods = Goods.objects.all().order_by(keyword)[data_start:data_end]
        
        else:
            goods = Goods.objects.all()[data_start:data_end]

        #判断是否进行模糊查询
        if text:
            #将text转为列表
            text = eval(text)
            goods_list = []
            for i in text:
                goods = Goods.objects.filter(Q(name__contains=i) | Q(desc__contains=i))
                for j in goods:
                    goods_list.append(j)
            
            #对商品列表进行去重
            goods_list= list(set(goods_list))
            print(goods_list)
            #获取总数量
            count = len(goods_list)
            #分页
            goods = goods_list[data_start:data_end]
        else:
            #查询所有商品个数
            count = Goods.objects.count()



        goods_ser = GoodsSer(goods,many=True)

        return Response({
            'data':goods_ser.data,
            'total':count
        })





import upyun


#又拍云移动
class Move(APIView):

    def get(self,request):
        #接收参数
        filename = request.GET.get('filename',None)
        #新建又拍云实例
        up = upyun.UpYun('zl1907a', username='zl956973503', password='ZmEoFxTDnbqnQsfUArFufDjPl9afXrod')
        print(filename)
        if filename:
            up.move('/'+filename,'/kaoshi/'+filename)
            return Response({
                'code':200,
            })
        else:
            return Response({
                'code':500,
            })




#又拍云创建文件夹
class Mkdirs(APIView):

    def get(self,request):
        #接收参数
        mkdir = request.GET.get('mkdir',None)
        #新建又拍云实例
        up = upyun.UpYun('zl1907a', username='zl956973503', password='ZmEoFxTDnbqnQsfUArFufDjPl9afXrod')
        
        if mkdir:
            up.mkdir('/'+mkdir+'/')
            return Response({
                'code':200,
            })
        else:
            return Response({
                'code':500,
            })



#又拍云删除
class Dels(APIView):

    def get(self,request):
        #接收参数
        filename = request.GET.get('filename',None)
        #新建又拍云实例
        up = upyun.UpYun('zl1907a', username='zl956973503', password='ZmEoFxTDnbqnQsfUArFufDjPl9afXrod')
        
        if filename:
            up.delete('/kaoshi/'+filename)
            return Response({
                'code':200,
            })
        else:
            return Response({
                'code':500,
            })




#又拍云上传
class UploadFileUpyuns(APIView):
    
    def post(self,request):

        img = request.FILES.get('file')

        up = upyun.UpYun('zl1907a', username='zl956973503', password='ZmEoFxTDnbqnQsfUArFufDjPl9afXrod')

        headers = { 'x-gmkerl-rotate': 'auto' }
        
        for chunk in img.chunks():
            res = up.put('./'+ img.name, chunk, checksum=True, headers=headers)

        #返回结果
        # return HttpResponse(json.dumps({'filename':img.name}),content_type='application/json')

        return Response({
            'filename':json.dumps({'filename':img.name})
        })















class UploadFiles(APIView):
    
    #post请求没有长度要求
    def post(self,request):
        #接收参数
        myfile = request.FILES.get('file')

        #设置时间戳
        time_stamp = str(int(time.time()))
        #设置图片名
        img_name = time_stamp + myfile.name
        #建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT,'',img_name),'wb')
        #写入
        for chunk in myfile.chunks():
            f.write(chunk)
        f.close()

        # 图像压缩
        img = cv2.imread(UPLOAD_ROOT+'/'+img_name)
        # jpg 压缩等级 0-100
        cv2.imwrite(UPLOAD_ROOT+'/'+img_name,img,[cv2.IMWRITE_JPEG_QUALITY,50])

        # 读图
        im = Image.open(UPLOAD_ROOT+'/'+img_name)
        #获取图片的长和宽
        im_width,im_height = im.size
        #设置水印字体和大小
        font = ImageFont.truetype(r'‪C:\Windows\Fonts\simkai.ttf',150)

        #生成画笔
        draw = ImageDraw.Draw(im)
        # #绘制  参数分别为坐标，文字，透明色
        draw.text((im_width-150*2,im_height-150),'周磊',fill=(76,234,124,180),font=font)
        # 存储图片
        im.save(UPLOAD_ROOT+'/'+img_name)

        return Response({
            'filename':img_name
        })






#md5加密方法
def make_password(mypass):

    #生成md5对象
    md5 = hashlib.md5()

    #转码 str强转mypass为字符串
    mypass_utf8 = str(mypass).encode(encoding="utf-8")

    #加密操作
    md5.update(mypass_utf8)

    #返回密文
    return md5.hexdigest()




#注册接口
class Registers(APIView):

    def get(self,request):

        #接收参数
        username = request.GET.get('username',None)
        password = request.GET.get('password',None)
        #排重操作
        user = User.objects.filter(username=username).first()

        if user:
            return Response({
                'code':403,
                'mes':'该用户名已经存在'
            })


        # 入库
        user = User(username=username,password=make_password(password))
        # 保存结果
        user.save()

        return Response({
            'code':200,
            'mes':'恭喜注册成功'
        })
    





#登陆接口
class Logins(APIView):

    def get(self,request):

        #接受参数
        username = request.GET.get('username',None)
        password = request.GET.get('password',None)

        #查询数据
        user = User.objects.filter(username=username,password=make_password(password)).first()

        if user:

            return Response({
                'code':200,
                'mes':'登陆成功',
                'uid':user.id,
                'username':user.username
            })
        else:
            return Response({
                'code':403,
                'mes':'用户名或密码错误'
                
            })



